package attendance

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/attendance"
	attendanceReq "github.com/flipped-aurora/gin-vue-admin/server/model/attendance/request"
)

type SignService struct {
}

// CreateSign 创建签到管理记录
// Author [piexlmax](https://github.com/piexlmax)
func (signService *SignService) CreateSign(sign *attendance.Sign) (err error) {
	err = global.GVA_DB.Create(sign).Error
	return err
}

// DeleteSign 删除签到管理记录
// Author [piexlmax](https://github.com/piexlmax)
func (signService *SignService) DeleteSign(ID string) (err error) {
	err = global.GVA_DB.Delete(&attendance.Sign{}, "id = ?", ID).Error
	return err
}

// DeleteSignByIds 批量删除签到管理记录
// Author [piexlmax](https://github.com/piexlmax)
func (signService *SignService) DeleteSignByIds(IDs []string) (err error) {
	err = global.GVA_DB.Delete(&[]attendance.Sign{}, "id in ?", IDs).Error
	return err
}

// UpdateSign 更新签到管理记录
// Author [piexlmax](https://github.com/piexlmax)
func (signService *SignService) UpdateSign(sign attendance.Sign) (err error) {
	err = global.GVA_DB.Model(&attendance.Sign{}).Where("id = ?", sign.ID).Updates(&sign).Error
	return err
}

// GetSign 根据ID获取签到管理记录
// Author [piexlmax](https://github.com/piexlmax)
func (signService *SignService) GetSign(ID string) (sign attendance.Sign, err error) {
	err = global.GVA_DB.Where("id = ?", ID).First(&sign).Error
	return
}

// GetSignInfoList 分页获取签到管理记录
// Author [piexlmax](https://github.com/piexlmax)
func (signService *SignService) GetSignInfoList(info attendanceReq.SignSearch, belongTo uint) (list []attendance.Sign, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&attendance.Sign{})
	db = db.Where("belong_to = ?", belongTo)
	var signs []attendance.Sign
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.ClassId != "" {
		db = db.Where("class_id = ?", info.ClassId)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&signs).Error
	return signs, total, err
}
